/**
 * 过滤器
 * */
package org.zmhhxl.sample3.oauth2.a.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

//@Configuration
//@Component
public class CustomAuthorizationFilter extends OncePerRequestFilter {

   /**
    * Same contract as for {@code doFilter}, but guaranteed to be
    * just invoked once per request within a single request thread.
    * See {@link #shouldNotFilterAsyncDispatch()} for details.
    * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
    * default ServletRequest and ServletResponse ones.
    *
    * @param request
    * @param response
    * @param filterChain
    */
   @Override
   protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      try {
         filterChain.doFilter(request, response);
      } catch (AccessDeniedException e) {
         handleAccessDeniedException(response, e);
      }
   }

   private void handleAccessDeniedException(HttpServletResponse response, AccessDeniedException e) throws IOException {
      response.setStatus(HttpStatus.FORBIDDEN.value());
      // 返回自定义的错误信息，例如JSON
      response.getWriter().write("{\"error\":\"Access Denied\",\"message\":\"" + e.getMessage() + "\"}");
   }

}
